import React, { createContext, useContext, useReducer, useEffect, ReactNode } from 'react'
import Taro from '@tarojs/taro'

// 用户状态接口
export interface UserInfo {
  id: string
  nickname: string
  avatarUrl?: string
  phone?: string
  [key: string]: any
}

// 认证状态接口
export interface AuthState {
  isLoggedIn: boolean
  userInfo: UserInfo | null
  token: string | null
  loading: boolean
}

// 初始状态
const initialState: AuthState = {
  isLoggedIn: false,
  userInfo: null,
  token: null,
  loading: true
}

// 动作类型
export type AuthAction =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'LOGIN_SUCCESS'; payload: { userInfo: UserInfo; token: string } }
  | { type: 'LOGOUT' }
  | { type: 'UPDATE_USER_INFO'; payload: UserInfo }
  | { type: 'INIT_AUTH_STATE'; payload: { userInfo: UserInfo | null; token: string | null } }

// reducer函数
function authReducer(state: AuthState, action: AuthAction): AuthState {
  switch (action.type) {
    case 'SET_LOADING':
      return {
        ...state,
        loading: action.payload
      }
    case 'LOGIN_SUCCESS':
      return {
        ...state,
        isLoggedIn: true,
        userInfo: action.payload.userInfo,
        token: action.payload.token,
        loading: false
      }
    case 'LOGOUT':
      return {
        ...state,
        isLoggedIn: false,
        userInfo: null,
        token: null,
        loading: false
      }
    case 'UPDATE_USER_INFO':
      return {
        ...state,
        userInfo: action.payload
      }
    case 'INIT_AUTH_STATE':
      return {
        ...state,
        isLoggedIn: !!(action.payload.token && action.payload.userInfo),
        userInfo: action.payload.userInfo,
        token: action.payload.token,
        loading: false
      }
    default:
      return state
  }
}

// Context接口
interface AuthContextType {
  state: AuthState
  dispatch: React.Dispatch<AuthAction>
  login: (userInfo: UserInfo, token: string) => void
  logout: () => void
  updateUserInfo: (userInfo: UserInfo) => void
  checkAuthState: () => void
}

// 创建Context
const AuthContext = createContext<AuthContextType | undefined>(undefined)

// AuthProvider组件
interface AuthProviderProps {
  children: ReactNode
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [state, dispatch] = useReducer(authReducer, initialState)

  // 初始化认证状态
  useEffect(() => {
    checkAuthState()
  }, [])

  // 检查认证状态
  const checkAuthState = () => {
    try {
      const token = Taro.getStorageSync('token')
      const userInfo = Taro.getStorageSync('userInfo')

      dispatch({
        type: 'INIT_AUTH_STATE',
        payload: { userInfo, token }
      })
    } catch (error) {
      console.error('检查认证状态失败:', error)
      dispatch({
        type: 'INIT_AUTH_STATE',
        payload: { userInfo: null, token: null }
      })
    }
  }

  // 登录函数
  const login = (userInfo: UserInfo, token: string) => {
    try {
      // 保存到本地存储
      Taro.setStorageSync('token', token)
      Taro.setStorageSync('userInfo', userInfo)

      // 更新全局数据（兼容现有代码）
      const app = Taro.getApp()
      if (!app.globalData) app.globalData = {}
      app.globalData.currentUserId = userInfo.id
      app.globalData.currentUserNickname = userInfo.nickname

      // 更新Context状态
      dispatch({
        type: 'LOGIN_SUCCESS',
        payload: { userInfo, token }
      })
    } catch (error) {
      console.error('登录状态保存失败:', error)
      throw error
    }
  }

  // 登出函数
  const logout = () => {
    try {
      // 清除本地存储
      Taro.removeStorageSync('token')
      Taro.removeStorageSync('userInfo')

      // 清除全局数据
      const app = Taro.getApp()
      if (app.globalData) {
        app.globalData.currentUserId = null
        app.globalData.currentUserNickname = null
      }

      // 更新Context状态
      dispatch({ type: 'LOGOUT' })
    } catch (error) {
      console.error('登出失败:', error)
      throw error
    }
  }

  // 更新用户信息
  const updateUserInfo = (userInfo: UserInfo) => {
    try {
      // 更新本地存储
      Taro.setStorageSync('userInfo', userInfo)

      // 更新全局数据
      const app = Taro.getApp()
      if (!app.globalData) app.globalData = {}
      app.globalData.currentUserId = userInfo.id
      app.globalData.currentUserNickname = userInfo.nickname

      // 更新Context状态
      dispatch({
        type: 'UPDATE_USER_INFO',
        payload: userInfo
      })
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    }
  }

  const contextValue: AuthContextType = {
    state,
    dispatch,
    login,
    logout,
    updateUserInfo,
    checkAuthState
  }

  return (
    <AuthContext.Provider value={contextValue}>
      {children}
    </AuthContext.Provider>
  )
}

// 自定义hook
export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}

// 便捷hooks
export function useAuthState() {
  const { state } = useAuth()
  return state
}

export function useUser() {
  const { state } = useAuth()
  return {
    userInfo: state.userInfo,
    isLoggedIn: state.isLoggedIn,
    loading: state.loading
  }
}